package com.lanbu.web.controller.camera;

import com.lanbu.camera.service.ICaCameraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 群聊天系统
 */
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {
    private static ICaCameraService caCameraService;

    private static PushService pushService;

    private static final Map<String, Session> sessionMap = new HashMap<>();

    @Autowired
    public void setCaCameraService(ICaCameraService caCameraService) {
        WebSocketServer.caCameraService = caCameraService;
    }

    @Autowired
    public void setPushService(PushService pushService) {
        WebSocketServer.pushService = pushService;
    }


    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println(sid + "连接");
        sessionMap.put(sid, session);
    }

    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        System.out.println(sid + "发送消息：" + message);
        sendToAllClient(message);
        List<String> cidList = caCameraService.selectCidListByCidId(sid);
        for (String cid : cidList) {
            pushService.pushMessage(message.split("HHHH")[1], message.split("HHHH")[0], "", cid);
        }
    }

    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println(sid + "断开连接");
        sessionMap.remove(sid);
    }

    public void sendToAllClient(String message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                //服务器向客户端发送消息
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

